/*
 * MainWindow.java
 *
 * Created on March 16, 2007, 10:52 PM
 */

package info.decamps.m2settings.swing;

import info.decamps.m2settings.SettingsXMLFileBinder;
import info.decamps.m2settings.model.Settings;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;

/**
 *
 * @author  regis
 */
public class MainWindow extends javax.swing.JFrame {
    private Logger log = Logger.getLogger(MainWindow.class);
    
    private SettingsXMLFileBinder xmlbind;
    private Settings settings; // a pointer to xmlbind.getSettings();
    
    /** Creates new form MainWindow */
    public MainWindow() {
        log.debug("welcome $Id$");
        reloadSettings();
        initComponents();
        
    }
    
    private void reloadSettings(final File settingsFile) throws FileNotFoundException, ValidationException, MarshalException {
        xmlbind=new SettingsXMLFileBinder(settingsFile);
        settings=xmlbind.getSettings();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane = new javax.swing.JTabbedPane();
        jPanelGeneral = new javax.swing.JPanel();
        jLabelLocalRepo = new javax.swing.JLabel();
        jTextFieldLocalRepo = new javax.swing.JTextField();
        jButtonLocalRepoBrowser = new javax.swing.JButton();
        jCheckBoxInteractiveMode = new javax.swing.JCheckBox();
        jCheckBoxOffline = new javax.swing.JCheckBox();
        jLabelProfiles = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanelMirrors = new javax.swing.JPanel();
        jMenuBar = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemLoad = new javax.swing.JMenuItem();
        jMenuItemQuit = new javax.swing.JMenuItem();
        jMenuItemExit = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("m2settings");

        jLabelLocalRepo.setText("Local Repository");

        initTextFieldLocalRepo();
        jTextFieldLocalRepo.setToolTipText("The local repository");
        jTextFieldLocalRepo.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent e) {jTextFieldLocalRepoDocumentChanged();}
            public void insertUpdate(javax.swing.event.DocumentEvent e) {jTextFieldLocalRepoDocumentChanged();}
            public void removeUpdate(javax.swing.event.DocumentEvent e) {jTextFieldLocalRepoDocumentChanged();}
        });

        jButtonLocalRepoBrowser.setText("...");
        jButtonLocalRepoBrowser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLocalRepoBrowserActionPerformed(evt);
            }
        });

        jCheckBoxInteractiveMode.setText("interactive mode");
        jCheckBoxInteractiveMode.setToolTipText("Whether Maven should attempt to interact with the user for input.");
        jCheckBoxInteractiveMode.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jCheckBoxInteractiveMode.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jCheckBoxInteractiveMode.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jCheckBoxInteractiveModeStateChanged(evt);
            }
        });

        jCheckBoxOffline.setText("offline");
        jCheckBoxOffline.setToolTipText("Indicate whether maven should operate in offline mode full-time.");
        jCheckBoxOffline.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jCheckBoxOffline.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jCheckBoxOffline.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jCheckBoxOfflineStateChanged(evt);
            }
        });

        jLabelProfiles.setText("Profiles");

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.setToolTipText("Configuration of build profiles for adjusting the build according to environmental parameters");
        jScrollPane1.setViewportView(jList1);

        org.jdesktop.layout.GroupLayout jPanelGeneralLayout = new org.jdesktop.layout.GroupLayout(jPanelGeneral);
        jPanelGeneral.setLayout(jPanelGeneralLayout);
        jPanelGeneralLayout.setHorizontalGroup(
            jPanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelGeneralLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanelGeneralLayout.createSequentialGroup()
                        .add(jLabelLocalRepo)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jTextFieldLocalRepo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButtonLocalRepoBrowser))
                    .add(jCheckBoxInteractiveMode)
                    .add(jCheckBoxOffline)
                    .add(jPanelGeneralLayout.createSequentialGroup()
                        .add(jLabelProfiles)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanelGeneralLayout.setVerticalGroup(
            jPanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelGeneralLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabelLocalRepo)
                    .add(jButtonLocalRepoBrowser)
                    .add(jTextFieldLocalRepo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jCheckBoxInteractiveMode)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jCheckBoxOffline)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabelProfiles)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        jTabbedPane.addTab("General", jPanelGeneral);

        org.jdesktop.layout.GroupLayout jPanelMirrorsLayout = new org.jdesktop.layout.GroupLayout(jPanelMirrors);
        jPanelMirrors.setLayout(jPanelMirrorsLayout);
        jPanelMirrorsLayout.setHorizontalGroup(
            jPanelMirrorsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 395, Short.MAX_VALUE)
        );
        jPanelMirrorsLayout.setVerticalGroup(
            jPanelMirrorsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 252, Short.MAX_VALUE)
        );

        jTabbedPane.addTab("tab2", jPanelMirrors);

        jMenuFile.setText("File");

        jMenuItemLoad.setText("Reload settings.xml");
        jMenuItemLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLoadActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemLoad);

        jMenuItemQuit.setText("Cancel and quit");
        jMenuItemQuit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemQuitActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemQuit);

        jMenuItemExit.setText("Save and exit");
        jMenuItemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExitActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemExit);

        jMenuBar.add(jMenuFile);

        setJMenuBar(jMenuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jTabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jTabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
private void jCheckBoxOfflineStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jCheckBoxOfflineStateChanged
    log.debug("offline="+jCheckBoxOffline.isSelected());
    settings.setOffline(jCheckBoxOffline.isSelected());
}//GEN-LAST:event_jCheckBoxOfflineStateChanged

    private void jCheckBoxInteractiveModeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jCheckBoxInteractiveModeStateChanged
        log.debug("Interactive mode="+jCheckBoxInteractiveMode.isSelected());
        settings.setInteractiveMode(jCheckBoxInteractiveMode.isSelected());
}//GEN-LAST:event_jCheckBoxInteractiveModeStateChanged
    
    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExitActionPerformed
        log.debug("Save and exit");
        try {
            xmlbind.saveSettings();
        } catch (MarshalException ex) {
            ex.printStackTrace();
        } catch (ValidationException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            alert("Cannot save settings",ex.getMessage());
        } finally{
            System.exit(1);
        }
        System.exit(0);
    }//GEN-LAST:event_jMenuItemExitActionPerformed
    
    private void jMenuItemQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemQuitActionPerformed
        log.debug("Quit");
        //TODO confirm dialog
        System.exit(0);
    }//GEN-LAST:event_jMenuItemQuitActionPerformed
    
    private void jButtonLocalRepoBrowserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLocalRepoBrowserActionPerformed
        JFileChooser jFileChooser1= new JFileChooser();
        jFileChooser1.setFileHidingEnabled(false);
        jFileChooser1.setDialogTitle("Select Maven Local repository");
        
        String currentRepo=settings.getLocalRepository();
        if (currentRepo!=null) {
            File currentM2Repo=new File(settings.getLocalRepository());
            log.debug("current is"+currentRepo);
            if (currentM2Repo!=null){
                jFileChooser1.ensureFileIsVisible(currentM2Repo);
                jFileChooser1.setSelectedFile(currentM2Repo);
                log.debug("selected");
            }
        }
        
        jFileChooser1.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        int returnVal = jFileChooser1.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File m2repo = jFileChooser1.getSelectedFile();
            log.debug("Opening: " + m2repo.getName() + "." );
            settings.setLocalRepository(m2repo.getPath());
            initTextFieldLocalRepo();
        } else {
            log.debug("Open command cancelled by user." );
        }
    }//GEN-LAST:event_jButtonLocalRepoBrowserActionPerformed
    
    private void jMenuItemLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLoadActionPerformed
        reloadSettings();
    }//GEN-LAST:event_jMenuItemLoadActionPerformed
    
    private void jTextFieldLocalRepoDocumentChanged() {
        if (jTextFieldLocalRepo.getText().length()==0) {
            settings.setLocalRepository(null);
        }     else {
            settings.setLocalRepository(jTextFieldLocalRepo.getText());
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                MainWindow thisClass = new MainWindow();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonLocalRepoBrowser;
    private javax.swing.JCheckBox jCheckBoxInteractiveMode;
    private javax.swing.JCheckBox jCheckBoxOffline;
    private javax.swing.JLabel jLabelLocalRepo;
    private javax.swing.JLabel jLabelProfiles;
    private javax.swing.JList jList1;
    private javax.swing.JMenuBar jMenuBar;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenuItem jMenuItemExit;
    private javax.swing.JMenuItem jMenuItemLoad;
    private javax.swing.JMenuItem jMenuItemQuit;
    private javax.swing.JPanel jPanelGeneral;
    private javax.swing.JPanel jPanelMirrors;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane;
    private javax.swing.JTextField jTextFieldLocalRepo;
    // End of variables declaration//GEN-END:variables
    
    private void initTextFieldLocalRepo() {
        jTextFieldLocalRepo.setText(settings.getLocalRepository());
    }
    
    /**
     * Reload the settings from settings.xml
     * In case of error, displays an JDialog alert, and constructs new settings
     **/
    private void reloadSettings()  {
        log.debug("Load settings.xml");
        try {
            xmlbind=new SettingsXMLFileBinder();
            xmlbind.loadSettings();
            settings=xmlbind.getSettings();
        } catch (FileNotFoundException e) {
            log.warn("settings.xml not found. Settings are initialized empty.");
            // if settings are null, return new.
            settings=xmlbind.getSettings();
        } catch (ValidationException e) {
            alert("Error loading settings","settings.xml corrupted");
        } catch (MarshalException e) {
            alert("Error loading settings","settings.xml XML invalid");
        }
        if (settings==null) {
            settings=new Settings();
            xmlbind.setSettings(settings);
        }
    }
    
    /**
     * Displays a JDialog alert.
     */
    public void alert(String title,String message) {
        JOptionPane jOptionPaneAlert=new JOptionPane();
        JDialog jDialogAlert=new JDialog(this);
        jDialogAlert.setTitle(title);
        jDialogAlert.add(jOptionPaneAlert);
        jOptionPaneAlert.setMessage(message);
        jDialogAlert.setVisible(true);
    }
}
